package com.itheima.filter;


import com.itheima.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //1.获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("本次拦截到的请求:{}",uri);
        //2.判断本次请求是否需要处理
        String[] urls = {
                "/login.do",
                "/login.html",
                "/css/**",
                "/elementuidemo/**",
                "/img/**",
                "/js/**",
                "/plugins/**",
                "/template/**",
        };
        boolean match =false;
        for (String url : urls) {
             match = antPathMatcher.match(url, uri);
            if (match) {
                //放行请求
                //3.如果不需要处理,直接放行
                filterChain.doFilter(request, response);
                return;
            }
        }
        //4.1 获得用户登录信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){//代表没有登录，正常拦截跳转到登录页面
            //5、如果未登录则返回未登录结果  跳转登录页面
            response.sendRedirect("/login.html");
            return;
        }
        filterChain.doFilter(request,response);
        return;
    }
}
